import pymongo
from tools.mongo_tool import MongoDbLink
from config.config import TEST_PORT,TEST_DB_HOST
mongo_link = pymongo.MongoClient(TEST_DB_HOST, TEST_PORT)
bs = mongo_link.bonded20231023
wf = mongo_link.workflow_dev
jw = MongoDbLink(TEST_DB_HOST,TEST_PORT,db_name='alpha-test')
flash_appointNo = ["AP1010171034207","AP1010171034061","AP1010166672952","AP1010166735527","AP1010168860224"
    ,"AP1010168857910","AP1010170875890","AP1010170878358","AP1010170893031","AP1010170869678","AP1010170893947"]
speed_appointNo = ["AP2311039624041","AP2309191313101","AP2311020921239","AP2311021183445","AP2311021272811",
                   "AP2308299015539","AP2308140245180","AP2311224682341"]


def get_jw_flash_stock(appointNo, type):
    """获取集物闪电预约单入库数量、销量、剩余库存"""
    stockids,goods,spus,skus,articleNo,size,instockqty,sale_order,buyer_return,buyer_refund = [],[],[],[],[],[],[],[],[],[]
    jw_dic= {}
    sold,total_in_stock_num,total_sold,total_return = 0,0,0,0
    order_list,return_list = [],[]
    stocks = jw.find('stocks',{"appointNo": appointNo,"appointType":type})
    for i in stocks:
        if i['spuId'] not in spus:
            spus.append(i['spuId'])
    for spu in spus:
        all_spus = jw.find('spus',{"spuId":spu})
        all_skus = jw.find('stocks',{"appointNo": appointNo,"spuId":spu,"appointType":type})
        for s in all_spus:
            articleNo.append(s['articleNumber'])
        for sku in all_skus:
            skus.append(sku['skuId'])
        for sku in skus:
            siz = jw.find('skus',{"skuId":sku})
            for o in siz:
                size.append(o['properties'].split('"尺码":"')[1].split('"}')[0])
            qty = jw.find("stocks",{"appointNo": appointNo,"skuId":sku,"appointType":type})
            for u in qty:
                stockids.append(str(u['_id']))
                instockqty.append(u['inStockQty'])
            total_in_stock_num=sum(instockqty)
        for stockid in stockids:
            sale_order.append(jw.count_documents("orders",{"stockId": stockid,"orderGroups":[3]}))
            sale_amount = jw.find('orders',{"stockId": stockid, "orderStatus": {"$in": ["3040", "4000"]}})
            for i in sale_amount:
                sold += int(i["platformData"]['sku_price']/100)
            orders = jw.find('orders',{"stockId": stockid})
            [order_list.append(i['orderNo']) for i in orders if i['orderNo'] not in order_list]
            for order in order_list:
                buyer_return.append(jw.count_documents('branddeliverreturns',{"order_no": order, "refund_status": 8000,"refund_type":{"$ne":10}}))
                buyer_refund.append(jw.count_documents('orderrefunds',{"orderNo": order, "status": "8000"}))
            return_list.append([sum(buyer_return), sum(buyer_refund),sold])
            buyer_return, buyer_refund,order_list,sold = [],[],[],0
        jw_dic['instock_qty'] = total_in_stock_num
        jw_dic['articleNo'] = articleNo[0]
        for i in range(len(size)):
            """dic的字段分别是入仓数量、销量、剩余库存 """
            all_order = sale_order[i] + return_list[i][0]+return_list[i][1]
            actual_stcok = instockqty[i] - sale_order[i]
            jw_dic[size[i]] = [instockqty[i], all_order, actual_stcok]
        return jw_dic


# for i in flash_appointNo:
#     print(get_jw_flash_stock(i,1))


def get_wf_flash_stock(invoiceNo):
    """获取workflow的集物闪电预约单库存、销量、剩余库存"""
    wf_dic,stockids,instock_num,articleNo,sizes,instock,total_sold,total_return ={},[],[],[],[],0,[],[]
    stocks= wf.stocks.find({"invoiceNo":invoiceNo})
    for i in stocks:
        instock_num.append(i['newStockNum'])
        articleNo.append(i['articleNumber'])
        sizes.append(i['size'])
    wf_dic['instock_qty'] =sum(instock_num)
    wf_dic['articleNo'] = articleNo[0]
    for size in sizes:
        [stockids.extend(i['originStockIds'])for i in wf.stocks.find({"size":size,"invoiceNo":invoiceNo})]
        for i in wf.stocks.find({"size":size,"invoiceNo":invoiceNo}):
            instock = i['newStockNum']
        for stockid in stockids:
            total_sold.append(wf.suborders.count_documents({"stockId": stockid}))
            total_return.append(wf.returnorders.count_documents({"stockId": stockid}))
            wf_dic[size] = [instock, sum(total_sold), instock - sum(total_sold) + sum(total_return)]
        stockids,total_sold,total_return = [],[],[]
    return wf_dic

# get_wf_stock("AP1010171034207")


def get_stock_out_orders(appointNo,type):
    """校验集物和wf调货出库订单数"""
    uniqueCodes,ck_order_list,wf_order_list,s,wf_orders= [],[],[],0,[]
    stocks = jw.find('stocks',{"appointNo": appointNo, "appointType": type})
    [uniqueCodes.append(i['uniqueCode']) for i in stocks]
    for uniquecode in uniqueCodes:
        ck_orders = jw.find('stock_out_records',{"uniqueCode":uniquecode,"outStockType":3})
        for i in ck_orders:
            if i['outStockOrderNo'] not in ck_order_list:
                ck_order_list.append(i['outStockOrderNo'])
    for ck in ck_order_list:
        wf_orders.append(wf.orders.count_documents({"outerOrderNos":{"$regex":ck}}))
    if len(ck_order_list) != sum(wf_orders):
        print('订单数据不匹配，集物订单数：{}，wf订单数：{}'.format(len(ck_order_list),sum(wf_orders)))
    else:
        print('订单数据匹配，集物订单数：{}，wf订单数：{}'.format(len(ck_order_list),sum(wf_orders)))
    return sum(wf_orders)


# s1 = 0
# for i in speed_appointNo:
#     s1+=get_stock_out_orders(i,1)
# print(s1)


def get_stock_out_suborders(appointNo,type):
    """校验集物和wf的调货出库子订单数量"""
    uniqueCodes,ck_order_list,jw_ck_order_list,s,wf_suborders,s_wf,a= [],[],[],0,[],0,0
    wf_ck_number,jw_ck_number,jw_total,stock_total = 0,0,0,0
    jw_ck_list,wf_ck_list =[],[]
    stocks = jw.find('stocks',{"appointNo": appointNo, "appointType": type})
    [uniqueCodes.append(i['uniqueCode']) for i in stocks]
    for uniquecode in uniqueCodes:
        ck_orders = jw.find('stock_out_records',{"uniqueCode":uniquecode,"outStockType":3})
        for i in ck_orders:
            jw_ck_number+=i['qty']
            if i['uniqueCode']+i['outStockOrderNo'] not in jw_ck_order_list:
                jw_ck_order_list.append(i['uniqueCode']+i['outStockOrderNo'])
        s += len(jw_ck_order_list)
        jw_total+=s
        stock_total+=jw_ck_number
        jw_ck_list.append({uniquecode:[s,jw_ck_number]})
        jw_ck_order_list,s,jw_ck_number = [],0,0
    print(jw_ck_list,jw_total,stock_total)
    for uno in uniqueCodes:
        wf_orders = wf.suborders.find({"outerOrderNo":{"$regex":uno}})
        for i in wf_orders:
            wf_suborders.append(i['outerOrderNo'])
            wf_ck_number+=i['count']
        s_wf += len(wf_suborders)
        a += len(wf_suborders)
        wf_ck_list.append({uno:[s_wf,wf_ck_number]})
        wf_suborders,s_wf,wf_ck_number = [],0,0
    print(wf_ck_list)
    if jw_ck_list == wf_ck_list:
        print('订单数据一致')
    else:
        print('订单数不匹配')
    return a


# s = 0
# for i in speed_appointNo:
#     s += get_stock_out_suborders(i,1)
# print(s)



# """集物、wf退货订单差异校验"""
# li =[]
# li1 = []
# z1,z2 = [],[]
# xx = jw.orders.find({"stockId":"6513e27336760c837caab698"})
# for i in xx:
#     li.append(i['orderNo'])
# for z in li:
#     li1.append(jw.branddeliverreturns.count_documents({"order_no":z,"refund_status":8000}))
#     if jw.branddeliverreturns.count_documents({"order_no":z,"refund_status":8000}) == 1:
#         z1.append(z)
# zz = wf.returnorders.find({"stockId":"6513e27336760c837caab698"})
# for i in zz:
#     z2.append(i['outerReturnOrderNo'])
# for i in z1:
#     if i not in z2:
#         print(i)
# print('zzzzzzzzzzzzzz')
# print(z2)


# """核对wf多余闪电结算"""
# li1,li = [],[]
# zz = wf.balancerecords.find({"outerOrderNo": {"$regex":"CK"}})
# [li1.append(i['outerOrderNo']) for i in zz]
# for z in li1:
#     if wf.settlements.count_documents({"outerOrderNo":z})==1:
#         li.append(z)
# if set(li1) == set(li):
#     print(True)
# else:
#     print(False)


# """调货订单销售额核对"""
# amount = 0
# jw_amount = 0
# zz = wf.suborders.find({"outerOrderNo": {"$regex":"CK"},"stockId":"64ed8f171c94bbc68dc7cff4","size":"42.5"})
# for i in zz:
#     amount+=i['orderAmount']
# print(amount)
# xx = jw.find("stock_out_records",{"uniqueCode":"S30402","outStockType":3})
# for i in xx:
#     jw_amount+=i['outStockPrice']*i['qty']/100
# print(jw_amount)


# """wf同步保税销售订单遗漏"""
# li,li1 = [],[]
# bs_orders = bs.orders.find({"orderGroups":{"$ne":[4]}})
# for i in bs_orders:
#     li.append(i['order_no'])
# wf_orders = wf.suborders.find({"salesChannelName":{"$regex":"保税仓"}})
# for z in wf_orders:
#     li1.append(z['outerOrderNo'])
# for n in li:
#     if n not in li1:
#         print(n)


def get_wf_flash_orders(appointNo):
    """校验wf得物闪电订单"""
    stockids,sizes,articlenumber,total_in_stock,wf_orders_list= [],[],[],[],[]
    wf_return_list,wf_sold_list = [],[]
    wf_dic = {}
    total_sold_amount = 0
    stocks = wf.stocks.find({"invoiceNo": appointNo})
    for i in stocks:
        stockids.extend(i['originStockIds'])
        sizes.append(i['size'])
        articlenumber.append((i['articleNumber']))
        total_in_stock.append(i['newStockNum'])
    total_in_stock_num = sum(total_in_stock)
    for stockid in stockids:
        wf_orders_list.append(wf.suborders.count_documents({"stockId":stockid}))
        wf_return_list.append(wf.returnorders.count_documents({"stockId":stockid}))
        wf_sold_order = wf.suborders.find({"stockId":stockid})
        for z in wf_sold_order:
            total_sold_amount+=z['orderAmount']
        wf_sold_list.append(total_sold_amount)
    total_sold_number = sum(wf_orders_list)
    for i in range(len(stockids)):
        actual_stock = total_in_stock[i] - wf_orders_list[i] + wf_return_list[i]
        wf_dic[sizes[i]] = [total_in_stock[i],wf_orders_list[i],actual_stock,wf_sold_list[i]]
    wf_dic['instock_qty'] = total_in_stock_num
    wf_dic['sold_qty'] = total_sold_number
    wf_dic['articleNo'] = articlenumber[0]
    return wf_dic


# for i in flash_appointNo:
#     print(get_wf_flash_orders(i))
#     print('')


def get_stock_in_number1(appointNo,type):
    """校验集物极速预约单入库、销售数据"""
    stockids,goods,spus,skus,articleNo,size,instockqty,success_order,buyer_return,buyer_refund = [],[],[],[],[],[],[],[],[],[]
    jw_dic= {}
    sold,total_in_stock_num = 0,0
    order_list,return_list,success_orderno_list = [],[],[]
    stocks = jw.find('stocks',{"appointNo": appointNo,"appointType":type})
    for i in stocks:
        if i['spuId'] not in spus:
            spus.append(i['spuId'])
    for spu in spus:
        all_spus = jw.find('spus',{"spuId":spu})
        all_skus = jw.find('stocks',{"appointNo": appointNo,"spuId":spu,"appointType":type})
        for s in all_spus:
            articleNo.append(s['articleNumber'])
        for sku in all_skus:
            skus.append(sku['skuId'])
        for sku in skus:
            siz = jw.find('skus',{"skuId":sku})
            for o in siz:
                size.append(o['properties'].split('"尺码":"')[1].split('"}')[0])
            qty = jw.find('stocks',{"appointNo": appointNo,"skuId":sku,"appointType":type})
            for u in qty:
                stockids.append(str(u['_id']))
                instockqty.append(u['inStockQty'])
            total_in_stock_num=sum(instockqty)
        for stockid in stockids:
            success_order.append(jw.count_documents('orders',{"stockId": stockid, "orderGroups": [3]}))
            orders = jw.find('orders',{"stockId": stockid,"orderStatus":{"$ne":"7000"}})
            [order_list.append(i['orderNo']) for i in orders if i['orderNo'] not in order_list]
            for order in order_list:
                buyer_return.append(jw.count_documents('branddeliverreturns',{"order_no": order, "refund_status": 8000}))
                buyer_refund.append(jw.count_documents('orderrefunds',{"orderNo": order, "status": "8000"}))
            return_list.append([sum(buyer_return), sum(buyer_refund)])
            buyer_return, buyer_refund,order_list = [],[],[]
        jw_dic['instock_qty'] = total_in_stock_num
        jw_dic['sold_qty'] = sum(success_order)
        for i in range(len(size)):
            """dic的字段分别是 入仓数量 jw销售订单数 直退订单数 客退订单数 销售总额"""
            # dic[size[i]] = [instockqty[i], sale_order[i],return_list[i][0],return_list[i][1],return_list[i][2]]
            actual_stcok = instockqty[i]-success_order[i]
            jw_dic[size[i]] = [instockqty[i],success_order[i]+return_list[i][0],actual_stcok]
        print(articleNo,jw_dic)
        jw_dic = {}
        articleNo, instockqty, size, skus, sale_order = [], [], [], [], []


# for i in speed_appointNo:
#     get_stock_in_number1(i,1)
#     print('')



def compare_stock_sold(appointno,type):
    a,b = get_jw_flash_stock(appointno, type),get_wf_flash_stock(appointno)
    if a == b:
        print('预约单{}库存销量数据一致'.format(appointno))
    else:
        print('预约单{}库存销量不一致'.format(appointno))
        print('集物预约单数据 : {}'.format(a))
        print('wrokflow预约单数据 : {}'.format(b))


for i in flash_appointNo:
    compare_stock_sold(i,1)

